/**
 * form comment HTML to be appended to the comment section
 * @method commentHTML
 * @param {string}pid post id
 * @param {string}user name of user who comment
 * @param {string}content content of the comment
 * @param {string}rate rate of the post
 */
function commentHTML(pid, user, content, rate) {
	var result = '';
	result += "<li><div class='comment_box'>" +
			"<div class='comment_author'>" + user +
			"<span class='comment_time'>Just Now</div>";
	if(rate != 0) {
		result += "<span class='comment_rate'><ul class='rating rate" + rate + "'>" +
				"<li class='one'>1</li><li class='two'>2</li><li class='three'>3</li><li class='four'>4</li><li class='five'>5</li>" +
				"</ul></span>";
				
	}
	result += "<p>" + content + "</p></div></li>";
	return result;
}


/**
 * clear comment form when the comment is added
 * @method clearComment
 */
function clearComment() {
	$("#user").val("");
	$("#comment_content").val("");
	$("#ratePost").removeClass().addClass("rating rate0");
}


/**
 * show newly added comment to the page without refreshing
 * @method addComment
 * @param {string}pid post id
 * @param {string}user name of user who comment
 * @param {string}content content of the comment
 */
function addComment(pid, user, content, rate) {
	$.ajax({
		url:"../api/addComment.py",
		type:"post",
		data:"id=" + pid + "&user=" + user + "&content=" + content,
		success:function(data) {
			
			if (data.length == 36) {	// comment added successful and its id is returned
				if( rate != 0 ) {
					addRate(pid, data, rate);	// add rate
				}
				clearComment();
				// append a "fake" comment box
				$("#comments").append(commentHTML(pid, user, content, rate)).show("fast");
			}
			else {
				$("#comment_error").html(data);
				clearComment();
			}
		},
		error:function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status);
            alert(thrownError);
		}
	});
}

/**
 * 
 */
function addRate(pid, cid, rate) {
	// add rate with post ID
	$.ajax({
		url:"http://cs4380.cs.cityu.edu.hk/51839597/webservice/ratePost.py",
		type:"post",
		data:"id=" + pid + "&rate=" + rate,
		success:function(data) {},
		error:function(xhr, ajaxOptions, thrownError) {}
	});
	// add rate with comment ID
	$.ajax({
		url:"http://cs4380.cs.cityu.edu.hk/51839597/webservice/ratePost.py",
		type:"post",
		data:"id=" + cid + "&rate=" + rate,
		success:function(data) {},
		error:function(xhr, ajaxOptions, thrownError) {}		 
	})
}